<?php
/**
 * Created by PhpStorm.
 * User: tangbl
 * Date: 2019/01/25
 * Time: 17:00
 */
namespace app\wechat\common\logic;
use think\Exception;

class Authwx{

    //获取微信授权地址
    public static function getUrl($appid,$redirect_uri='',$scope='snsapi_userinfo',$state=''){

        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope={$scope}&state={$state}#wechat_redirect";
    }

    /**
     * 拉取用户信息(需scope为 snsapi_userinfo)
     * @param $accessToken
     * @param $openid
     * @param string $scope
     * @return array|mixed
     * @throws Exception
     */
    public static function gUser($accessToken,$openid,$scope='snsapi_userinfo'){

        if($scope=='snsapi_userinfo'){
            $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$accessToken}&openid={$openid}&lang=zh_CN";
            $r = file_get_contents($url);
            $rArr = json_decode($r,true);
            if(empty($rArr['errcode'])){
                return $rArr;
            }else{
                throw new Exception($rArr['errmsg'], -1);
            }
        }
        throw new Exception('the scope is not snsapi_userinfo!', -1);
    }

    /**
     * 获取access
     * @param $appid
     * @param $secret
     * @param $code
     * @return false|string
     * @throws \think\Exception
     */
    public static function getAccess($appid, $secret, $code){

        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code";
        $r = file_get_contents($url);
        $rArr = json_decode($r,true);
        if(empty($rArr['errcode'])){
            return $rArr;
        }else{
            throw new Exception($rArr['errmsg'], -1);
        }
    }
}